import 'dart:async';

import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import '../../../components/app_conifg.dart';

class PhoneBindController extends BaseController {
  ///用户身份id
  String openId = '';

  ///是否同意用户协议
  bool isAgree = false;

  ///手机号
  String phoneNumber = '';

  ///验证码
  String validCode = '';

  Timer? timer;

  int countdown = 0;
  String countdownTxt = '发送验证码';

  @override
  void onInit() {
    super.onInit();
    openId = Get.parameters['openId']!;
    startCountdown();
  }

  @override
  void onClose() {
    super.onClose();
    if (timer != null) {
      timer!.cancel();
    }
  }

  ///输入手机号
  void onInputPhone(String phone) {
    phoneNumber = phone;
  }

  ///输入验证码
  void onInputCode(String code) {
    validCode = code;
  }

  void startCountdown() {
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (countdown >= 1) {
        countdown--;
        countdownTxt = "重新发送(${countdown.toString()}s)";
      } else {
        countdownTxt = '发送验证码';
      }
      update();
    });
  }

  ///发送验证码
  void sendCode() {
    if (!Tools.checkEmpty(phoneNumber)) {
      Tools.showToast('请输入手机号');
      return;
    }
    if (countdown > 0) {
      Tools.showToast('$countdown秒后可重新获取');
      return;
    }
    Tools.showLoading(title: '请稍候');
    Network.getMsgCode(phoneNumber, 'bindingAccount').then((value) {
      Tools.hideLoading();
      if (value) {
        Tools.showToast('验证码已发送');
        countdown = 60;
      }
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///校验手机号
  bool checkPhone() {
    if (!Tools.checkEmpty(phoneNumber)) {
      Tools.showToast('请输入手机号');
      return false;
    }
    return true;
  }

  ////校验是否同意用户协议
  bool checkAgree() {
    if (isAgree) {
      return true;
    } else {
      Tools.showModal(
        cancelText: '不同意',
        confirmText: '同意',
        isRichText: true,
        richText: Text.rich(TextSpan(children: [
          const TextSpan(text: '请阅读并同意'),
          TextSpan(text: '《用户协议》', style: setTextStyle(15, FontWeight.w500, ThemeConfig.tagColor)),
          TextSpan(text: '《隐私协议》', style: setTextStyle(15, FontWeight.w500, ThemeConfig.tagColor)),
        ])),
        onConfirm: (tag) {
          isAgree = true;
          update();
          SmartDialog.dismiss(tag: tag);
        },
      );
      return false;
    }
  }

  ///完成绑定
  void completeBind() {
    if (!checkPhone()) {
      return;
    }
    if (!checkAgree()) {
      return;
    }
    Map<String, dynamic> params = {};
    params['account'] = phoneNumber;
    params['sid'] = AppData.sid;
    params['smsCode'] = validCode;
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['openId'] = openId;
    params['registrationId'] = AppData.jPushRegistrationID;
    params['lastLoginPlatform'] = GetPlatform.isIOS ? 2 : 1;
    Tools.showLoading(title: '正在绑定...');
    Network.bindAccount(params).then((value) {
      Tools.hideLoading();
      AppData.phoneNumber = phoneNumber;
      AppData.tokenName = value['tokenName'];
      AppData.tokenValue = value['tokenValue'];
      EventMgr.send(EventType.refreshLogin);
      Get.until((route) => Get.currentRoute == Routes.main);
      Tools.showToast('绑定成功');
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }
}
